package com.nanhai.buddhist.college.module.collegebase.service.colleges;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanhai.buddhist.college.framework.common.exception.util.ServiceExceptionUtil;
import com.nanhai.buddhist.college.framework.common.pojo.PageResult;
import com.nanhai.buddhist.college.framework.common.util.number.NumberUtils;
import com.nanhai.buddhist.college.framework.datapermission.core.annotation.DataPermission;
import com.nanhai.buddhist.college.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.nanhai.buddhist.college.framework.security.core.util.SecurityFrameworkUtils;
import com.nanhai.buddhist.college.module.collegebase.controller.admin.colleges.vo.CollegesCreateReqVO;
import com.nanhai.buddhist.college.module.collegebase.controller.admin.colleges.vo.CollegesExportReqVO;
import com.nanhai.buddhist.college.module.collegebase.controller.admin.colleges.vo.CollegesPageReqVO;
import com.nanhai.buddhist.college.module.collegebase.controller.admin.colleges.vo.CollegesUpdateReqVO;
import com.nanhai.buddhist.college.module.collegebase.convert.colleges.CollegesConvert;
import com.nanhai.buddhist.college.module.collegebase.dal.dataobject.colleges.CollegesDO;
import com.nanhai.buddhist.college.module.collegebase.dal.mysql.colleges.CollegesMapper;
import com.nanhai.buddhist.college.module.collegebase.enums.ErrorCodeConstants;
import com.nanhai.buddhist.college.module.collegebase.util.DateChangeUtil;
import com.nanhai.buddhist.college.module.system.api.user.AdminUserApi;
import com.nanhai.buddhist.college.module.system.api.user.dto.AdminUserRespDTO;
import jodd.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 学校管理--学院 Service 实现类
 *
 * @author 开发
 */
@Service
@Validated
public class CollegesServiceImpl implements CollegesService {

    @Resource
    private CollegesMapper collegesMapper;

    @Resource
    private AdminUserApi adminUserApi;

    @Override
    public String createColleges(CollegesCreateReqVO createReqVO) {

//        String userId = SecurityFrameworkUtils.getLoginUserId();
//        CommonResult<AdminUserRespDTO> users = adminUserApi.getUser(userId);
//
//        String permissionJson = users.getData().getPermissionJson();
//        UserPermissionListVo userPermissionListVo = JsonUtils.parseObject(permissionJson, UserPermissionListVo.class);
//
//        if(Objects.isNull(userPermissionListVo) || !userPermissionListVo.isCollegeAll()){
//            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COLLEGES_NOT_ALLOW_CREATE);
//        }

        // 插入
        CollegesDO colleges = CollegesConvert.INSTANCE.convert(createReqVO);

        // 检验学院昵称和学院代码唯一性
        final Long nameCount = collegesMapper.selectCount(new LambdaQueryWrapper<CollegesDO>().eq(CollegesDO::getCollegeName, colleges.getCollegeName()));
        if (ObjectUtil.isNotNull(nameCount) && nameCount > 0) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COLLEGE_NAME_HAVE_EXISTS);
        }
        final Long codeCount = collegesMapper.selectCount(new LambdaQueryWrapper<CollegesDO>().eq(CollegesDO::getCollegeCode, colleges.getCollegeCode()));
        if (ObjectUtil.isNotNull(codeCount) && codeCount > 0) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COLLEGE_CODE_HAVE_EXISTS);
        }

        colleges.setCollegeNumber(NumberUtils.getCodeByServ("XY"));
        collegesMapper.insert(colleges);

        adminUserApi.saveUserCollegeData(SecurityFrameworkUtils.getLoginUserId(), 0, "0", colleges.getId());
        adminUserApi.initUserCollegeData(SecurityFrameworkUtils.getLoginUserId());

        // 返回
        return colleges.getId();
    }

    @Override
    public void updateColleges(CollegesUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateCollegesExists(updateReqVO.getId());
        // 更新
        CollegesDO updateObj = CollegesConvert.INSTANCE.convert(updateReqVO);

        // 检验学院昵称和学院代码唯一性
        final Long nameCount = collegesMapper.selectCount(new LambdaQueryWrapper<CollegesDO>()
                .eq(CollegesDO::getCollegeName, updateObj.getCollegeName())
                .ne(CollegesDO::getId, updateReqVO.getId()));
        if (ObjectUtil.isNotNull(nameCount) && nameCount > 0) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COLLEGE_NAME_HAVE_EXISTS);
        }
        final Long codeCount = collegesMapper.selectCount(new LambdaQueryWrapper<CollegesDO>()
                .eq(CollegesDO::getCollegeCode, updateObj.getCollegeCode())
                .ne(CollegesDO::getId, updateReqVO.getId()));
        if (ObjectUtil.isNotNull(codeCount) && codeCount > 0) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COLLEGE_CODE_HAVE_EXISTS);
        }
        collegesMapper.updateById(updateObj);
        adminUserApi.initUserCollegeData(SecurityFrameworkUtils.getLoginUserId());
    }

    @Override
    public void deleteColleges(String id) {
        // 校验存在
        this.validateCollegesExists(id);

        if (ObjectUtil.isNotNull(adminUserApi.checkRoleUser(id).getData()) && adminUserApi.checkRoleUser(id).getData()) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.CHECK_USE_EXISTS);
        }

        // 删除
        collegesMapper.deleteById(id);

        adminUserApi.initUserCollegeData(SecurityFrameworkUtils.getLoginUserId());
    }

    private void validateCollegesExists(String id) {
        if (collegesMapper.selectById(id) == null) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.COLLEGES_NOT_EXISTS);
        }
    }

    @Override
    @DataPermission(enable = false)
    public CollegesDO getColleges(String id) {
        return collegesMapper.selectById(id);
    }

    @Override
    @DataPermission(enable = false)
    public List<CollegesDO> getCollegesList(Collection<String> ids) {

        return com.nanhai.buddhist.college.framework.common.util.collection.CollectionUtils.isEmpty(ids) ? Collections.emptyList() : collegesMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<CollegesDO> getCollegesPage(CollegesPageReqVO pageReqVO) {
        if (com.xkcoding.http.util.StringUtil.isNotEmpty(pageReqVO.getOpeningEndTime())) {
            pageReqVO.setOpeningEndTimeDate(DateChangeUtil.stringToDateEnd(pageReqVO.getOpeningEndTime()));
        }
        if (com.xkcoding.http.util.StringUtil.isNotEmpty(pageReqVO.getOpeningStartTime())) {
            pageReqVO.setOpeningStartTimeDate(DateChangeUtil.stringToDateStart(pageReqVO.getOpeningStartTime()));
        }
        return collegesMapper.selectPage(pageReqVO);
    }

    @Override
    public List<CollegesDO> getCollegesList(CollegesExportReqVO exportReqVO) {
        return collegesMapper.selectList(exportReqVO);
    }

    @Override
    @DataPermission(enable = false)
    public List<CollegesDO> getCollegesAllList() {
        return collegesMapper.selectList(new LambdaQueryWrapperX<>());
    }

    @Override
    public List<CollegesDO> getCollegesAllListByPermission() {
        return collegesMapper.selectList(new LambdaQueryWrapperX<>());
    }

    @Override
    public List<AdminUserRespDTO> getAllAdminUserList(String findStr) {
        List<AdminUserRespDTO> data = adminUserApi.getAllList().getData();
        if (CollectionUtil.isEmpty(data)) {
            return new ArrayList<AdminUserRespDTO>();
        }
        // 如果传入字符做模糊查询
        if (StringUtil.isNotBlank(findStr)) {
            return data.stream().filter(s -> s.getNickname().contains(findStr)).collect(Collectors.toList());
        }
        return data;
    }

}
